<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('收入信息表功能')"/>
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: bootstrap-fileinput-js"/>
</head>
<!--人脸识别弹出信息的样式-->
<style>
    .card {
        background-color: #f8f9fa; /* 浅灰色背景 */
        border: 1px solid #ddd; /* 边框 */
        border-radius: 8px; /* 圆角 */
    }

    .card-title {
        color: #007bff; /* 标题颜色 */
    }

    .list-group-item {
        border: none; /* 移除列表项的边框 */
        background-color: transparent; /* 透明背景 */
    }

    .list-group-item strong {
        color: #333; /* 键的颜色 */
    }
</style>

<style>
    /*<!--  人脸识别的css样式-->*/
    #fileForm {
        background-color: #f7f7f7;
        padding: 20px;
        border-radius: 8px;
    }

    .image-container {
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f7f7f7;
    }


    .image-preview {
        margin-top: 20px;
        text-align: center;
    }

    .image-preview img {
        max-width: 100%;
        height: auto;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 5px;
    }

    select {
        margin-left: 5%;
        width: 40%;
        height: 40%;
        border: 1px solid #333333;;
        display: block;
        position: relative;
        padding: 0 0 0 160px;
    }

    p {
        margin-top: 1%;
        float: left;
        text-align: center;
    }

    #add, #stop {
        height: 100px;
        margin-top: 5%;
        margin-left: 25%;

    }

    #btnAdd {
        margin-left: 23%;
        margin-top: 2.5%;
    }

    #sealBtn {
        margin-left: 15%;
        margin-top: 2.5%;
    }

    #unsealBtn {
        margin-left: 10%;
        margin-top: 2.5%;
    }

    #btnExport {
        margin-left: 42.5%;
        margin-top: 0.01%;

    }
</style>

<style>

    .form-item {
        width: 100%;
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #333333;
        margin-bottom: 20px;
        margin-top: 2%;
        margin-left: 18%;
        box-sizing: border-box;
    }

    .form-item label {
        width: 126px;
        text-align: right;
    }


    .form-item input {
        width: 200px;
        height: 40px;
        line-height: 40px;
        border: 1px solid #cccccc;
        padding-left: 14px;
        box-sizing: border-box;
        margin-left: 18px;
    }

    /* 这是原生的input框，给他透明隐藏，然后定位让文件上传的按钮覆盖它 */
    #fileInput {
        width: 40px;
        margin-left: 5px;
        filter: Alpha(opacity=0);
        -moz-opacity: 0;
        opacity: 0;
        position: absolute;
        right: 50px;
        z-index: 2;


    }

    /* 这是主要的，文件上传按钮的样式 */
    .file-btn {
        width: 40px;
        height: 40px;
        background: rgba(230, 242, 255, 1);
        border: 1px solid rgba(167, 210, 255, 1);
        text-align: center !important;
        line-height: 40px;
        color: #333333;
        position: relative;
        top: 2px;
        left: 20px;
    }

    /* 单行文字截断，展示文件名的input框用的 */
    #applyLicense {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

    }

</style>

<body class="gray-bg">


<div class="container-div1">

    <ul id="myTab" class="nav nav-tabs" style="height: 100%">
        <li class="active" style="height: 100%">
            <a href="#add" data-toggle="tab" style="height: 100%;line-height: 35px">
                新建年份表单
            </a>
        </li>
        <li style="height: 100%">
            <a href="#stop" data-toggle="tab" style="height: 100%;line-height: 35px">
                收入信息封停-解封
            </a>
        </li>
        <li style="height: 100%">
            <a href="#import" data-toggle="tab" style="height: 100%;line-height: 35px">导入原始采集收入表
            </a>
        </li>
        <li style="height: 100%">
            <a href="#check" data-toggle="tab" style="height: 100%;line-height: 35px">人脸识别
            </a>
        </li>
    </ul>
    <div id="myTabContent" class="tab-content">
        <div class="tab-pane fade in active" id="add">
            <p>年份</p>
            <select id="year" class="form-select" aria-label="Default select example">
                <option selected></option>
                <option></option>
            </select>
            <br>
            <a class="btn btn-info" onclick="newDate()" id="btnAdd">
                新建
            </a>
        </div>


        <div class="tab-pane fade" id="stop">
            <p>年份</p>
            <select id="seal" class="form-select" aria-label="Default select example">
                <option selected></option>
                <option></option>
            </select>
            <br>
            <a class="btn btn-success" onclick="seal()" id="sealBtn">
                封停
            </a>
            <a class="btn btn-info" onclick="unseal()" id="unsealBtn">
                解封
            </a>
        </div>
        <div class="tab-pane fade" id="import">

            <br>
            <a class="btn btn-info" onclick="exportTemplate()">
                <i class="fa fa-upload"></i> 导出原始收入收入采集表模板
            </a>

            <form method="post" id="fileForm">
                <div class="form-item">
                    <label for="applyLicense"> 选择文件</label>
                    <input readonly style="width: 30%" id="applyLicense" type="text" placeholder="请上传文件"
                           autocomplete="off">
                    <input id="fileInput" type="file" name="file" accept="excel/xls,excel/xlsx">
                    <label for="fileInput" class="file-btn">浏览</label>
                </div>
                <br>
            </form>
            <div class="w">
                <button class="btn btn-info" onclick="exportData()" id="btnExport">
                    导入
                </button>
            </div>
        </div>

        <!--人脸识别2.0-->
        <div class="tab-pane fade" id="check">
            <div class="container mt-4">
                <div class="row justify-content-center">
                    <div class="col-md-6">
                        <div class="image-container mb-3"
                             style="width: 300px; height: 300px; margin: auto; border: 1px solid #ddd; border-radius: 8px; overflow: hidden;">
                            <img id="previewImage" src="#" alt="Image preview"
                                 style="display: none; width: 100%; height: 100%; object-fit: cover;"/>
                        </div>
                        <div id="imageURL" style="text-align: center; margin-bottom: 10px;">Image URL will appear here
                        </div>
                        <form method="post" id="fileForm" style="margin-top: 10px">
                            <div class="form-group text-center">
                                <label for="fileInput" class="btn btn-primary">上传图片</label>
                                <input type="file" class="form-control-file d-none" id="fileInput" name="file"
                                       accept="image/jpeg, image/png">
                                <button type="button" class="btn btn-info ml-2" onclick="faceDetection()">识别</button>
                                <button type="button" class="btn btn-info ml-2" onclick="getFarmerInfo()">查询个人信息
                                </button>

                                <!--                <button onclick="getFarmerInfoWithFixedName()">获取韩振江的信息</button>-->

                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 模态窗口 -->
        <div class="modal fade" id="farmerInfoModal" tabindex="-1" role="dialog" aria-labelledby="farmerInfoModalLabel"
             aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="farmerInfoModalLabel">农户信息</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <!-- 在这里插入农户信息 -->
                        <div id="farmerInfoContent"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>


        <!--    <div className="col-sm-8">-->
        <!--      <select name="sex" className="form-control m-b" th:with="type=${@dict.getType('base_family_type')}">-->
        <!--        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>-->
        <!--      </select>-->
        <!--    </div>-->


        <th:block th:include="include :: footer"/>
        <script th:inline="javascript">

            var prefix = ctx + "system/function";
            var name; // 人脸识别返回的人名

            function newDate() {
                var options = $("#year option:selected"); //获取选中的option
                var year = options.text();
                $.ajax({
                    url: prefix + "/add",
                    type: "POST",
                    data: year,
                    success: function (result) {
                        //使用jQuery的$.modal方法，调用msgReload参数,用于弹出一个带有提示信息的模态框
                        $.modal.msgReload("新建成功，正在刷新...")
                    }
                })
            }

            // 显示上传图片的js代码
            $(document).ready(function () {
                $('#fileInput').change(function () {
                    readURL(this);
                });
            });

            // 显示上传图片的js代码
            function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $('#previewImage').attr('src', e.target.result);
                        $('#previewImage').show();
                    }

                    reader.readAsDataURL(input.files[0]);
                }
            }

            // 美化  JavaScript图片预览功能
            document.addEventListener("DOMContentLoaded", function () {
                document.getElementById('fileInput').addEventListener('change', function () {
                    if (this.files && this.files[0]) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            document.getElementById('previewImage').src = e.target.result;
                            document.getElementById('previewImage').style.display = 'block';
                        };
                        reader.readAsDataURL(this.files[0]);
                    }
                });
            });

            // 人脸识别  传路径和识别的JS
            document.getElementById('fileInput').addEventListener('change', function (event) {
                var file = event.target.files[0];
                var reader = new FileReader();
                reader.onload = function (e) {
                    document.getElementById('previewImage').src = e.target.result;
                    document.getElementById('previewImage').style.display = 'block';
                    document.getElementById('imageURL').textContent = e.target.result; // 显示图片 URL
                };
                var element = document.getElementById('imageURL');
                element.classList.add('hidden');
                // reader.readAsDataURL(file);
            });

            function faceDetection() {
                var fileInput = document.getElementById('fileInput');
                var file = fileInput.files[0];

                if (file) {
                    var formData = new FormData();
                    formData.append('image', file); // 'image' 是后端期望的字段名

                    // 使用 AJAX 发送 FormData
                    $.ajax({
                        url: '/face_detection/img_face',
                        type: 'POST',
                        data: formData,
                        processData: false,  // 告诉jQuery不要处理发送的数据
                        contentType: false,  // 告诉jQuery不要设置Content-Type请求头
                        success: function (response) {
                            if (response.code = 500) {
                                $.modal.alertWarning(response.msg);
                            }
                            console.log('Response:', response);
                            name = response.data.name || "null";
                            $.modal.alertSuccess(name);
                        },
                        error: function (error) {
                            console.error('Error:', error);
                        }
                    });
                } else {
                    console.log("No file selected");
                }
            }

            function getFarmerInfo() {
                $.ajax({
                    url: '/face_detection/getFarmerByName',
                    type: 'POST',
                    data: {Name: name},
                    success: function (farmer) {
                        console.log('Farmer Info:', farmer);
                        // displayFarmerInfo(farmer);
                        // 在这里用获取到的数据渲染页面
                        displayFarmerInfoInModal(farmer);
                    },
                    error: function (error) {
                        console.error('Error:', error);
                    }
                });
            }

            // 创建映射函数
            function mapFamilyType(familyTypeCode) {
                const familyTypeMap = {
                    "1": "脱贫户",
                    "2": "脱贫不稳定户",
                    "3": "边缘易致贫户",
                    "4": "突发严重困难户",
                    "5": "一般户",
                };
                return familyTypeMap[familyTypeCode] || familyTypeCode;
            }

            function mapNatVillage(natVillageCode) {
                const natVillageMap = {
                    "1": "大六合",
                    "2": "后六合",
                    "3": "姜家瑶",
                    "4": "六家子东",
                    "5": "六家子西",
                    "6": "龙凤泡",
                    "7": "西石头",
                    "8": "小舍力",
                };
                return natVillageMap[natVillageCode] || natVillageCode;
            }

            function displayFarmerInfoInModal(farmer) {
                // 应用映射
                var mappedFamilyType = mapFamilyType(farmer.familyType);
                var mappedNatVillage = mapNatVillage(farmer.natVillage);

                var infoHtml = `
    <div class="card">
        <div class="card-body">
            <h5 class="card-title">农户信息</h5>
            <ul class="list-group list-group-flush">
                <li class="list-group-item"><strong>家庭类型：</strong>${mappedFamilyType}</li>
                <li class="list-group-item"><strong>农户 ID：</strong>${farmer.fid}</li>
                <li class="list-group-item"><strong>姓名：</strong>${farmer.name}</li>
                <li class="list-group-item"><strong>自然村：</strong>${mappedNatVillage}</li>
                <li class="list-group-item"><strong>电话：</strong>${farmer.phone}</li>
<!--   查出来的farmer对象里没有num             <li class="list-group-item"><strong>家中人口数：</strong></li>-->
            </ul>
        </div>
    </div>
`;

                $('#farmerInfoContent').html(infoHtml);
                $('#farmerInfoModal').modal('show');

            }

            function uploadImage() {
                var formData = new FormData();
                formData.append('file', $('#fileInput')[0].files[0]);
                formData.append('imagePath', imagePath); // 添加 imagePath 参数
                $.ajax({
                    url: "/common/upload",
                    type: 'post',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        // 图片上传成功，获得图片路径
                        var imagePath = response.filePath;
                        executePythonScript(imagePath); // 调用执行 Python 脚本的函数
                    },
                    error: function (error) {
                        console.log("上传失败", error);
                    }
                });
            }

            function executePythonScript(imagePath) {
                $.ajax({
                    url: "/api/python/run",
                    type: 'post',
                    data: formData,
                    success: function (result) {
                        // 显示 Python 脚本执行结果
                        $('#resultContainer').html('<p>识别结果：' + result + '</p>');
                    },
                    error: function (error) {
                        console.log("执行失败", error);
                    }
                });
            }

            $("#btnExport").click(function () {
                uploadImage(); // 点击识别按钮时开始上传图片
            });


            //待改进
            // function exportData_image() {
            //   var formData = new FormData();
            //   if ($('#fileInput')[0].files[0] == null) {
            //     $.modal.alertWarning("请先选择文件");
            //     return false;
            //   }
            //   var name = $("#fileInput").val();
            //   if (name === '' || (!$.common.endWith(name, '.jpeg') && !$.common.endWith(name, '.png') &&!$.common.endWith(name, '.jpg'))) {
            //     $.modal.msgWarning("请选择后缀为 “jpeg”或“png”或“jpg”的图片文件。");
            //     return false;
            //   }
            //
            //   formData.append('fileName', $("input[name='file']").val());
            //   formData.append('file', $('#fileInput')[0].files[0]);
            // }

            function exportData() {
                //$.valiate.form()表示调用jQuery的validate插件进行表单验证,查看文件是否符合格式
                //如果验证成功就执行uploadfile
                if ($.validate.form()) {
                    uploadFile();
                }
            }

            function uploadFile() {
                //用于上传文件
                var formData = new FormData();
                //取叫fileInput的第一个元素的第一个文件
                if ($('#fileInput')[0].files[0] == null) {
                    $.modal.alertWarning("请先选择文件路径");
                    return false;
                }
                //获取文件名
                var name = $("#fileInput").val();
                if (name === '' || (!$.common.endWith(name, '.xls') && !$.common.endWith(name, '.xlsx'))) {
                    $.modal.msgWarning("请选择后缀为 “xls”或“xlsx”的文件。");
                    return false;
                }
//<写两个键值对，将文件名与文件写到对应的键里面>
                formData.append('fileName', $("input[name='file']").val());
                formData.append('file', $('#fileInput')[0].files[0]);
                $.ajax({
                    url: prefix + "/common/upload",
                    type: 'post',
                    cache: false, //禁用缓存功能
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function (result) {
                        $.modal.msgReload("导入成功，正在刷新...", 1)
                    },
                    complete: function (XMLHttpRequest, textStatus, msg) {
                        if (XMLHttpRequest.status === 11111) {
                            $.modal.msgReload(XMLHttpRequest.responseJSON.msg, 0)
                        }
                    }
                });

            }

            function exportTemplate() {
                window.location.href = prefix + "/export";
            }

            function seal() {
                var options = $("#seal option:selected"); //获取选中的option
                $.ajax({
                    url: prefix + "/seal",
                    data: {
                        'flag': 'false',
                        'year': options.text()
                    },
                    type: 'GET',
                    success: function (result) {
                        $.modal.msgReload("封停成功，正在刷新...")
                    }
                })
            }

            function unseal() {
                var options = $("#seal option:selected"); //获取选中的option
                $.ajax({
                    url: prefix + "/seal",
                    data: {
                        'flag': 'true',
                        'year': options.text()
                    },
                    type: 'GET',
                    success: function (msg) {
                        $.modal.msgReload("解封成功，正在刷新...")
                    }
                })
            }

            //这里本人用的是jq，大致意思就是：监听文件上传的内容，如果内容改变了，就把它的内容放到用来展示的input里。
            changeImg();

            function changeImg() {
                $("#fileInput").change(function () {
                    $("#applyLicense").val($("#fileInput").val());
                })
            }

            getYear();

            function getYear() {
                var tmp = '[[${year}]]';

                var year = parseInt(tmp.substring(1, tmp.length - 1));


                var yearSelect = document.getElementById("year");
                yearSelect.options[0].text = year;
                yearSelect.options[1].text = year + 1;
                var sealSelect = document.getElementById("seal");
                sealSelect.options[0].text = year;
                sealSelect.options[1].text = year - 1;
            }
        </script>
</body>
</html>
